import React from "react";
import Relay from "react-relay";
import DelQiniuFileMutation from "./DelQiniuFileMutation"; // 删除图片
import {Upload,Button} from 'antd';
import Config from "../../../../util/Config"
export default class A extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fileList:[]
        };

        this.url = Config.qiuniu;

        this.updataFile = this.updataFile.bind(this);
        this.onFilChange = this.onFilChange.bind(this);
        this.picRemove = this.picRemove.bind(this);
    }

    updataFile = (file)=>{
        const token = this.props.token,
            date = new Date().getTime();
        const obj = {file,token,key:`${(date+"").slice(-5)}_${file.name}`};
        return {file,token,key:`${(date+"").slice(-5)}_${file.name}`};
    };

    onFilChange({file,fileList,event}){
        // 只有在成功的时候才设置url
        if(file.status === "done"){
            for(let i in fileList){
                if(fileList[i].status === "done"){
                    fileList[i].url = this.url + fileList[i].response.key + `?attname=${fileList[i].name}`
                }
            }
            this.props.callBack(file,fileList);
        }else{
            this.props.callBack(file,fileList);
        };
    };

    picRemove(file){
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: file.response.key
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {}
                }
            }
        )
    };

    render() {
        const {filePlugin,className,fileList,defaultList,disabled} = this.props;
        let {isShowTrigger} = this.props;

        if(isShowTrigger === undefined) { isShowTrigger = true; }

        return  <Upload
                className={className}
                {...filePlugin}
                fileList={fileList}
                data={this.updataFile}
                onChange={this.onFilChange}
                onRemove={this.picRemove}
                defaultList={defaultList}
                disabled={disabled}
            >
                {
                    this.props.children
                }
            </Upload>
    };
}
